<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="会员账号" prop="username">
        <el-input
          v-model="queryParams.username"
          placeholder="请输入会员账号"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="手机号码" prop="mobile">
        <el-input
          v-model="queryParams.mobile"
          placeholder="请输入手机号码"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="会员等级" prop="levelId">
        <el-select v-model="queryParams.levelId" placeholder="请选择会员等级" clearable>
          <el-option
            v-for="level in levelOptions"
            :key="level.levelId"
            :label="level.levelName"
            :value="level.levelId"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="会员状态" clearable>
          <el-option
            v-for="dict in dict.type.sys_normal_disable"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['member:member:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['member:member:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['member:member:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['member:member:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="memberList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="会员编号" align="center" prop="memberId" />
      <el-table-column label="会员账号" align="center" prop="username" />
      <el-table-column label="会员昵称" align="center" prop="nickname" />
      <el-table-column label="手机号码" align="center" prop="mobile" />
      <el-table-column label="会员等级" align="center" prop="levelName" />
      <el-table-column label="积分" align="center" prop="points" />
      <el-table-column label="状态" align="center" prop="status">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.sys_normal_disable" :value="scope.row.status"/>
        </template>
      </el-table-column>
      <el-table-column label="创建时间" align="center" prop="createTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.createTime) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['member:member:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['member:member:remove']"
          >删除</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-key"
            @click="handleResetPwd(scope.row)"
            v-hasPermi="['member:member:resetPwd']"
          >重置密码</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-money"
            @click="handlePoints(scope.row)"
            v-hasPermi="['member:member:edit']"
          >修改积分</el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改会员对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="600px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="会员账号" prop="username">
          <el-input v-model="form.username" placeholder="请输入会员账号" :disabled="form.memberId != undefined"/>
        </el-form-item>
        <el-form-item label="会员昵称" prop="nickname">
          <el-input v-model="form.nickname" placeholder="请输入会员昵称" />
        </el-form-item>
        <el-form-item label="手机号码" prop="mobile">
          <el-input v-model="form.mobile" placeholder="请输入手机号码" />
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="form.email" placeholder="请输入邮箱" />
        </el-form-item>
        <el-form-item label="会员等级" prop="levelId">
          <el-select v-model="form.levelId" placeholder="请选择会员等级">
            <el-option
              v-for="level in levelOptions"
              :key="level.levelId"
              :label="level.levelName"
              :value="level.levelId"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="form.status">
            <el-radio
              v-for="dict in dict.type.sys_normal_disable"
              :key="dict.value"
              :label="dict.value"
            >{{dict.label}}</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" type="textarea" placeholder="请输入内容" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 重置密码对话框 -->
    <el-dialog :title="'重置密码'" :visible.sync="resetPwdOpen" width="400px" append-to-body>
      <el-form ref="resetPwdForm" :model="resetPwdForm" :rules="resetPwdRules" label-width="100px">
        <el-form-item label="新密码" prop="password">
          <el-input v-model="resetPwdForm.password" placeholder="请输入新密码" type="password" />
        </el-form-item>
        <el-form-item label="确认密码" prop="confirmPassword">
          <el-input v-model="resetPwdForm.confirmPassword" placeholder="请再次输入新密码" type="password" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitResetPwd">确 定</el-button>
        <el-button @click="cancelResetPwd">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 修改积分对话框 -->
    <el-dialog :title="'修改积分'" :visible.sync="pointsOpen" width="400px" append-to-body>
      <el-form ref="pointsForm" :model="pointsForm" :rules="pointsRules" label-width="100px">
        <el-form-item label="当前积分" prop="points">
          <el-input v-model="pointsForm.points" disabled />
        </el-form-item>
        <el-form-item label="积分变动" prop="pointsChange">
          <el-input-number v-model="pointsForm.pointsChange" :min="-999999" :max="999999" />
        </el-form-item>
        <el-form-item label="变动原因" prop="remark">
          <el-input v-model="pointsForm.remark" type="textarea" placeholder="请输入变动原因" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitPoints">确 定</el-button>
        <el-button @click="cancelPoints">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listMember, getMember, delMember, addMember, updateMember, resetMemberPwd, updateMemberPoints } from "@/api/member/member";
import { listMemberLevel } from "@/api/member/level";

export default {
  name: "Member",
  dicts: ['sys_normal_disable'],
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 会员表格数据
      memberList: [],
      // 会员等级选项
      levelOptions: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 是否显示重置密码弹出层
      resetPwdOpen: false,
      // 是否显示修改积分弹出层
      pointsOpen: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        username: null,
        mobile: null,
        levelId: null,
        status: null
      },
      // 表单参数
      form: {},
      // 重置密码表单参数
      resetPwdForm: {},
      // 修改积分表单参数
      pointsForm: {},
      // 表单校验
      rules: {
        username: [
          { required: true, message: "会员账号不能为空", trigger: "blur" },
          { min: 3, max: 20, message: '用户账号长度必须介于 3 和 20 之间', trigger: 'blur' }
        ],
        nickname: [
          { required: true, message: "会员昵称不能为空", trigger: "blur" }
        ],
        mobile: [
          { pattern: /^1[3|4|5|6|7|8|9][0-9]\d{8}$/, message: "请输入正确的手机号码", trigger: "blur" }
        ],
        email: [
          { type: "email", message: "请输入正确的邮箱地址", trigger: ["blur", "change"] }
        ],
        levelId: [
          { required: true, message: "会员等级不能为空", trigger: "change" }
        ]
      },
      // 重置密码表单校验
      resetPwdRules: {
        password: [
          { required: true, message: "新密码不能为空", trigger: "blur" },
          { min: 6, max: 20, message: '密码长度必须介于 6 和 20 之间', trigger: 'blur' }
        ],
        confirmPassword: [
          { required: true, message: "确认密码不能为空", trigger: "blur" },
          {
            validator: (rule, value, callback) => {
              if (value !== this.resetPwdForm.password) {
                callback(new Error("两次输入的密码不一致"));
              } else {
                callback();
              }
            },
            trigger: "blur"
          }
        ]
      },
      // 修改积分表单校验
      pointsRules: {
        pointsChange: [
          { required: true, message: "积分变动不能为空", trigger: "blur" }
        ],
        remark: [
          { required: true, message: "变动原因不能为空", trigger: "blur" }
        ]
      }
    };
  },
  created() {
    this.getList();
    this.getLevelOptions();
  },
  methods: {
    /** 查询会员列表 */
    getList() {
      this.loading = true;
      listMember(this.queryParams).then(response => {
        this.memberList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    /** 获取会员等级选项 */
    getLevelOptions() {
      listMemberLevel().then(response => {
        this.levelOptions = response.rows;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 取消重置密码按钮
    cancelResetPwd() {
      this.resetPwdOpen = false;
      this.resetPwdForm = {};
    },
    // 取消修改积分按钮
    cancelPoints() {
      this.pointsOpen = false;
      this.pointsForm = {};
    },
    // 表单重置
    reset() {
      this.form = {
        memberId: null,
        username: null,
        nickname: null,
        mobile: null,
        email: null,
        levelId: null,
        status: "0",
        remark: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.memberId)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加会员";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const memberId = row.memberId || this.ids
      getMember(memberId).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改会员";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.memberId != null) {
            updateMember(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addMember(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const memberIds = row.memberId || this.ids;
      this.$modal.confirm('是否确认删除会员编号为"' + memberIds + '"的数据项？').then(function() {
        return delMember(memberIds);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 重置密码按钮操作 */
    handleResetPwd(row) {
      this.resetPwdForm = {
        memberId: row.memberId,
        username: row.username
      };
      this.resetPwdOpen = true;
    },
    /** 提交重置密码 */
    submitResetPwd() {
      this.$refs["resetPwdForm"].validate(valid => {
        if (valid) {
          resetMemberPwd(this.resetPwdForm).then(response => {
            this.$modal.msgSuccess("修改成功");
            this.resetPwdOpen = false;
          });
        }
      });
    },
    /** 修改积分按钮操作 */
    handlePoints(row) {
      this.pointsForm = {
        memberId: row.memberId,
        points: row.points,
        pointsChange: 0,
        remark: null
      };
      this.pointsOpen = true;
    },
    /** 提交修改积分 */
    submitPoints() {
      this.$refs["pointsForm"].validate(valid => {
        if (valid) {
          updateMemberPoints(this.pointsForm).then(response => {
            this.$modal.msgSuccess("修改成功");
            this.pointsOpen = false;
            this.getList();
          });
        }
      });
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('member/member/export', {
        ...this.queryParams
      }, `member_${new Date().getTime()}.xlsx`)
    }
  }
};
</script> 